
#include "app_message.h"
#include <string.h>
#include "cJSON.h"
#include <stdlib.h>
#include "app_common.h"
#include "log.h"

/**
 *  @brief  把字节数组转换成json字符串
 * @param  data   字节数组
 * @param  len  字节数组长度
 * @return  json字符串
 */
char *app_message_bytes_to_json(char *data, int len)
{
    // 获得是什么连接
    int conn_type = data[0];
    int id_len = data[1];
    int msg_len = data[2];
    char id_bytes[id_len]; // id的字节数组
    memcpy(id_bytes, data + 3, id_len);
    char msg_bytes[msg_len];
    // 获得消息数组
    memcpy(msg_bytes, data + 3 + id_len, msg_len);
    // 转换为16进制字符串
    char *id_hexstr = app_common_bytes_to_hexstr(id_bytes, id_len);
    char *msg_hexstr = app_common_bytes_to_hexstr(msg_bytes, msg_len);

    // 创建json对象
    cJSON *json = cJSON_CreateObject();
    // 添加属性
    cJSON_AddNumberToObject(json, "conn_type", conn_type);
    cJSON_AddStringToObject(json, "id", id_hexstr);
    cJSON_AddStringToObject(json, "msg", msg_hexstr);
    char *json_str = cJSON_PrintUnformatted(json);

    cJSON_Delete(json);
    // 释放释放内存
    free(id_hexstr);
    free(msg_hexstr);
    return json_str;
}

/**
 *  @brief  把json字符串转换成字节数组
 * @param  json   json字符串
 * @param  buffer   字节数组容器
 * @param  buffer_len  字节容器的长度
 * @return  转换的字节数
 */
int app_message_json_to_bytes(char *json, char *buffer, int buffer_len)
{
    //转换为JSON对象
    cJSON *json_obj = cJSON_Parse(json);
    //获取json的属性
    cJSON *conn_type_obj = cJSON_GetObjectItem(json_obj, "conn_type");
    cJSON *id_obj = cJSON_GetObjectItem(json_obj, "id");
    cJSON *msg_obj = cJSON_GetObjectItem(json_obj, "msg");
    //获取对应属性的id和msg
    int conn_type = conn_type_obj->valueint;
    char*id_hexstr=id_obj->valuestring;
    char *msg_hexstr = msg_obj->valuestring;
    int id_len = strlen(id_hexstr) / 2;
    char id_bytes[id_len];
    //字符串转16进制
    id_len=app_common_hexstr_to_bytes(id_hexstr, id_bytes, id_len);
    //消息字符串转16进制
    int msg_len = strlen(msg_hexstr) / 2;
    char msg_bytes[msg_len];
    msg_len=app_common_hexstr_to_bytes(msg_hexstr, msg_bytes, msg_len);

    
       // * 3  把3个值拼接为字节数组
   int bytes_len = 3+id_len+msg_len;
   if(bytes_len>buffer_len)
   {
     log_error("buffer_len is too small");
     return -1;
   }
   buffer[0] = conn_type;
   buffer[1] = id_len;
   buffer[2] = msg_len;
   memcpy(buffer+3,id_bytes,id_len);
   memcpy(buffer+3+id_len,msg_bytes,msg_len);

   return bytes_len;
}